package TCPDemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPEchoServer {
    private ServerSocket socket = null;

    public TCPEchoServer(int port) throws IOException {
        this.socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");

        ExecutorService executorService = Executors.newCachedThreadPool();//线程数目动态变化

        while (true) {
            Socket clientSocket = socket.accept();

//            //一次只能处理一个客户端的请求
//            processConnection(clientSocket);

//            //使用多线程，一个服务器一次能处理多个客户端的请求
//            Thread thread = new Thread(() -> {
//                processConnection(clientSocket);
//            });
//            thread.start();

            //使用线程池，一个服务器一次能处理多个客户端的请求
            executorService.submit(() -> {
                processConnection(clientSocket);
            });
        }
    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s, %s] 客户端上线\n", clientSocket.getInetAddress(), clientSocket.getPort());

        try (InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                if (!scanner.hasNext()) {
                    System.out.printf("[%s %s] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //获取请求
                String request = scanner.next();

                //根据请求计算响应
                String response = process(request);

                //发送响应
                printWriter.println(request);
                //刷新缓冲区
                printWriter.flush();

                //打印日志
                System.out.printf("[%s %s] request: %s, response: %s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer tcpEchoServer = new TCPEchoServer(9090);
        tcpEchoServer.start();
    }
}
